package com.j.lemon.learn.basic.utils;

import com.alibaba.fastjson.JSONPath;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

public class JsonUtils {

    private static final transient Logger logger = LoggerFactory.getLogger(JsonUtils.class);

    public static final SimpleDateFormat shortFormatter = new SimpleDateFormat("yyyy-MM-dd");

    public static final SimpleDateFormat longFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static ObjectMapper objectMapper = new ObjectMapper();

    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    static {
        // TODO locale - sensitive
        objectMapper.setDateFormat(longFormatter);
    }

    public static Object deepClone(Object obj) {
        return parseJson(toJson(obj), obj.getClass());
    }

    public static <T> T parseJson(String content, Class<T> clazz) {
        try {
            return objectMapper.readValue(content, clazz);
        }
        catch (Exception e) {
            logger.error("parseJson", e);
        }
        return null;
    }

    public static <V, K> V parseJson(String content, Class<V> VClass, Class<K> kClass) {
        try {
            JavaType type = objectMapper.getTypeFactory().constructParametricType(VClass, kClass);
            return objectMapper.readValue(content, type);
        } catch (Exception e) {
            logger.error("parseJson", e);
        }
        return null;
    }

    public static List parseList(String content) {
        try {
            return objectMapper.readValue(content, List.class);
        }
        catch (Exception e) {
            logger.error("parseList", e);
        }
        return null;
    }

    public static Map parseMap(String content) {
        try {
            return objectMapper.readValue(content, Map.class);
        }
        catch (Exception e) {
            logger.error("parseMap", e);
        }
        return null;
    }

    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        }
        catch (IOException e) {
            logger.error("toJson", e);
        }
        return null;
    }
}
